package com.ruoyi.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.springframework.util.ClassUtils;

import java.io.*;
import java.nio.charset.Charset;

public class PDFUtil {
    private static Configuration configuration = null;

    static {
        configuration = new Configuration();
        //freemarker的模板目录
        try {
            configuration.setDirectoryForTemplateLoading(new File(ClassUtils.getDefaultClassLoader().getResource("template").getPath().substring(1)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出pdf
     *
     * @param templateView-freemarker模板相对路径
     * @param os-输出流
     * @param model-模板所需要的数据
     * @throws Exception
     */
    public static void export(String templateView,Object model,String temp) throws Exception {
        FileOutputStream tempOs = new FileOutputStream(temp);
        Template template = configuration.getTemplate(templateView);
//        Template template = configuration.getTemplate(htmlTmp);
        StringWriter result = new StringWriter();
        template.process(model, result);
        String htmlData = result.toString();//模版变量
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, tempOs);

        //添加水印和页码
        PDFBuilder builder = new PDFBuilder();
        writer.setPageEvent(builder);
        //打开文件
        document.open();
        //html文件解析
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(htmlData.getBytes()), Charset.forName("UTF-8"));
        //关闭
        document.close();
    }

    public static void main(String[] args) throws Exception {
        //html模板路径只支持相对路径
        String templateView="CERTIFICATION_TOWER.html";
        //生成pdf的路径支持绝对路径和相对路径
        String temp="G:/git/company";
        //中间模板对应数据model可为null
        export(templateView,null,temp);
    }
}
